﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;
using System.IO;
using System.Text;

namespace RastinArgham.CRM.Web
{
    public partial class agents_sale : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();

            if (!securityManager.IsActionPermitted("agents_sale_report"))
                Response.Redirect("~/access_denied.aspx");

            if (!Page.IsPostBack)
            {
                lblAgentSales.Text = "0";
                lblResellerSales.Text = "0";
                LoadAgents();
            }
        }

        private void LoadAgents()
        {
            List<aspnet_Users> users = securityManager.FindUsersByRole("agents");
            drpAgents.DataSource = users;
            drpAgents.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search("gridview");
        }

        private void Search(string output)
        {
            if (drpAgents.SelectedValue == "-1")
                return;

            Guid agentId = Guid.Parse(drpAgents.SelectedValue);

            List<Guid> resellers = crmRepository.GetUsersByParent(agentId).Select(u => u.UserId).ToList();

            List<Order> orders = crmRepository.GetActiveOrdersByDate(txtStartDate.Text.ToDateTime().Value, txtEndDate.Text.ToDateTime().Value);
            List<Order> agentOrders = orders.Where(o => o.Contact.AccountManagerId == agentId).ToList();
            List<Order> resellerOrders = orders.Where(o => resellers.Contains(o.Contact.AccountManagerId)).ToList();

            lblAgentSales.Text = UIHelper.FormatString(agentOrders.Sum(o => o.TotalPrice));
            lblResellerSales.Text = UIHelper.FormatString(resellerOrders.Sum(o => o.TotalPrice));

            List<Order> result = new List<Order>();
            result.AddRange(agentOrders);
            result.AddRange(resellerOrders);

            lblCount.Text = result.Count().ToString();

            if (output == "gridview")
            {
                gvOrders.Visible = true;
                gvOrders.DataSource = result;
                gvOrders.DataBind();
            }
            else if (output == "excel")
            {
                gvOrders.Visible = false;
                string temp_path = "~/tmp";
                ExportToExcel(result, temp_path);
            }  
        }

        protected void gvOrders_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOrders.PageIndex = e.NewPageIndex;
            Search("gridview");
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            Search("excel");
        }

        public void ExportToExcel(List<Order> orders, string tempDirectory)
        {
            ExportToExcel ee = new Mani.Common.ExportToExcel();
            string path = tempDirectory + "/" + Guid.NewGuid() + ".xls";
            StringBuilder ExcelContent = new StringBuilder();

            ExcelContent.Append(ee.InitializeExcel(Server.MapPath("~/Styles.config")));
            ExcelContent.Append(ee.StartWorkSheet(1));
            ExcelContent.Append(ee.StartTable());
            ExcelContent.Append(ee.StartRow());

            ExcelContent.Append(ee.NewCell("کد"));
            ExcelContent.Append(ee.NewCell("عنوان شخص"));
            ExcelContent.Append(ee.NewCell("محصول"));
            ExcelContent.Append(ee.NewCell("نام سرویس"));
            ExcelContent.Append(ee.NewCell("مبلغ"));
            ExcelContent.Append(ee.NewCell("مالیات ( درصد )"));
            ExcelContent.Append(ee.NewCell("مبلغ کل ( ریال )"));
            ExcelContent.Append(ee.NewCell("وضعیت"));
            ExcelContent.Append(ee.NewCell("آخرین اپراتور"));

            ExcelContent.Append(ee.FinishRow());

            foreach (var o in orders)
            {
                ExcelContent.Append(ee.StartRow());

                ExcelContent.Append(ee.NewCell(o.OrderId.ToString()));
                ExcelContent.Append(ee.NewCell(o.ContactTitle));
                ExcelContent.Append(ee.NewCell(o.ProductName));
                ExcelContent.Append(ee.NewCell(o.ServiceName));
                ExcelContent.Append(ee.NewCell(o.Price.ToString()));
                ExcelContent.Append(ee.NewCell(o.TaxPercent.ToString()));
                ExcelContent.Append(ee.NewCell(o.TotalPrice.ToString()));
                ExcelContent.Append(ee.NewCell(o.Status));
                ExcelContent.Append(ee.NewCell(o.OperatorName));

                ExcelContent.Append(ee.FinishRow());
            }

            ExcelContent.Append(ee.FinishTable());
            ExcelContent.Append(ee.FinishWorksheet());
            ExcelContent.Append(ee.FinishFile());

            ee.SaveFile(ExcelContent, Server.MapPath(path));

            Response.Redirect(path);
        }
    }
}